package com.vogue.supplymall.common.domain.validate;

import java.io.Serializable;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.HashMap;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.exception.FormatIncorrectException;

@SuppressWarnings("serial")
public class RegexValidator implements ConstraintValidator<Regex, String>,Serializable{

	@Autowired
	protected MessageSourceUtils messageSourceUtils;
	
	public static final Map<String, String> keyMap = new HashMap<String, String>(){{
		put("tel", "^((\\+86)|(86))?(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\\d{8})$"); //手机号码
		put("email", "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\\\.[a-zA-Z0-9_-]+)+$");//邮箱
		put("vernum", "^[vV]{1}[0-9]+$");//系统版本号
	}};
	
	private String attrName = "name";
	
	private String regexcontent = "tel";
	
	@Override
	public void initialize(Regex constraintAnnotation) {
		// TODO Auto-generated method stub
		attrName = messageSourceUtils.getMessage(com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
				+ constraintAnnotation.name(), null);
		regexcontent = StringUtils.isEmpty(constraintAnnotation.regexcontent()) ? regexcontent : constraintAnnotation.regexcontent();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		// TODO Auto-generated method stub
		String regex = keyMap.get(regexcontent) == null ? regexcontent : keyMap.get(regexcontent);
		boolean isMatch = Pattern.matches(regex, value);
		if(!isMatch) {
			throw new FormatIncorrectException(attrName);
		}
		return true;
	}

}
